package net.bithappens.hnqe.mapper.graphxml;

import java.util.TimerTask;

import net.bithappens.hnqe.InvalidDataException;
import net.bithappens.hnqe.cache.ICacheManipulate;
import net.bithappens.hnqe.mapper.OperationInstructions;

import org.apache.log4j.Logger;

public class CronJob extends TimerTask{

	private Logger log = Logger.getLogger(this.getClass());
	
	private String instanceId;
	
	private OperationInstructions instructions;
	
	private ICacheManipulate cache;
	
	private XMLGraphDataParser graphParser;
	
	
	public CronJob(String instanceId, ICacheManipulate cache, OperationInstructions instructions, XMLGraphDataParser graphDataParser){
		
		this.instanceId = instanceId;
		
		this.cache = cache;
		
		this.instructions = instructions;
		
		this.graphParser = graphDataParser;
		
	}
	
	
	@Override
	public void run() {
		
		synchronized (graphParser) {
						
			try {
				graphParser.parse();
			} catch (Exception e) {
				log.error("Couldn't run graphPare for instance \""+instanceId+"\" due to"+ e.getMessage(),e);
			}
			
			try {
				
				if(graphParser.getNodesToWrite().size() > 0){
					cache.pushNodes(instanceId, graphParser.getNodesToWrite(), instructions);
				}
				
			} catch (Exception e) {
				log.error("Graph nodes couldn't be written due to: "+e.getMessage(), e);
			}

			try {

				if(graphParser.getRelationsToWrite().size() > 0){
					cache.pushRelations(instanceId, graphParser.getRelationsToWrite(), instructions);
				}

			} catch (Exception e) {
				log.error("Graph relations couldn't be written due to: "+e.getMessage(), e);
			}
		}		
	}
}
